import React, { useRef } from 'react';
import { Form, Select } from 'antd';
import { useSetState, useMount } from 'ahooks';
import _ from 'lodash';
import { default as EchoBox } from '../../../EchoBox';
import { getSecondMenuList } from '@/services/power';
import { HttpCode } from '@/utils/contacts';

const { Option } = Select;
const FormItem = Form.Item;

export default ({ form, echoApp, firstMenuListModel, defaultFlag }) => {
  const menuRef = useRef(null);
  const [state, setState] = useSetState({
    firstMenuId: '',
    dropdownList: [], //应用名称下拉查询
    secondMenuList: [], // 二级菜单查询
    firstMenuList: [], //回显的一级菜单
  });

  useMount(() => {
    getInit();
  });

  useMount(() => {
    const arr = _.reduce(
      firstMenuListModel,
      (t, v) => {
        if (v.operationType === 3) {
          return t;
        } else {
          return [...t, v];
        }
      },
      [],
    );
    setState({
      firstMenuId: arr.length ? arr[0].firstMenuId : '',
      dropdownList: arr,
    });
  });

  const getInit = async () => {
    menuRef?.current?._changeLoading(true);
    let response = await getSecondMenuList();
    menuRef?.current?._changeLoading(false);
    if (response && response.statusCode === HttpCode.SUCCESS) {
      setState({
        secondMenuList: response?.data || [],
      });
    } else {
      setState({
        secondMenuList: [],
      });
    }
  };

  const handleEcho = (list) => {
    let _sort = 0;
    const _sortArr = _.map(list, (_v) => {
      if (_v.operationType !== 3) {
        _v.sort = _sort;
        _sort = _sort + 1;
      } else {
        _v.sort = -1;
      }
      return _v;
    });
    const _list = _.map(firstMenuListModel, (_v) => {
      if (_v.firstMenuId === state.firstMenuId) {
        _v.secondMenuList = _sortArr;
      }
      return _v;
    });
    echoApp && echoApp(_list);
  };

  const _onChange = (value) => {
    setState({
      firstMenuId: value,
    });
  };

  return (
    <Form form={form} colon={false} requiredMark={false} labelAlign="left" layout={'vertical'}>
      <FormItem label="一级菜单" rules={[{ message: '选择一级菜单' }]}>
        <Select style={{ width: 150 }} value={state.firstMenuId} onChange={_onChange}>
          {state.dropdownList.map((app) => {
            return (
              <Option value={app.firstMenuId} key={app.firstMenuId}>
                {app.name}
              </Option>
            );
          })}
        </Select>
      </FormItem>
      <FormItem label="二级菜单">
        <EchoBox
          ref={menuRef}
          checkList={state.secondMenuList}
          firstMenuId={state.firstMenuId}
          handleEcho={handleEcho}
          echoList={firstMenuListModel}
          echoType="secMenu"
          defaultFlag={defaultFlag}
        />
      </FormItem>
    </Form>
  );
};
